package com.gnerv.battle.boot.security.config.filter;

import com.gnerv.battle.boot.security.exception.VerificationCodeErrorAccessDeniedException;
import com.gnerv.battle.boot.security.service.AbstractVerificationCodeService;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;

/**
 * @author Gnerv LiGen
 */
@Slf4j
public class BattleCustomVerificationCodeFilter extends GenericFilterBean {

    private final RequestMatcher requiresAuthenticationRequestMatcher;

    @Resource
    private AbstractVerificationCodeService verificationCodeService;

    public BattleCustomVerificationCodeFilter(String defaultFilterProcessesUrl) {
        this.requiresAuthenticationRequestMatcher = new AntPathRequestMatcher(defaultFilterProcessesUrl, "POST");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        boolean matches = requiresAuthenticationRequestMatcher.matches((HttpServletRequest) servletRequest);
        if (matches) {
            boolean verify = verificationCodeService.verify(servletRequest, servletResponse);
            if (!verify) {
                // 验证码对比不通过
                throw new VerificationCodeErrorAccessDeniedException("Verification Code Error !");
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
